namespace Digitalmes.Application.Sys.Dicts.Commands;

/// <summary>
/// 更新字典数据项命令。
/// </summary>
public record UpdateDictItemCommand(long Id, SysDictItemDto DictItem) : IRequest<IResult<bool>>;

internal sealed class UpdateDictItemCommandHandler(IRepository<SysDictItem> repo) : IRequestHandler<UpdateDictItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateDictItemCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.Label == request.DictItem.Label && m.DictId == request.DictItem.DictId && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("字典项标签已存在");
        }

        var item = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (item == null)
        {
            return Result.Failure("未找到要更新的字典项");
        }

        item.Label = request.DictItem.Label;
        item.Value = request.DictItem.Value;
        item.Order = request.DictItem.Order;
        item.Status = request.DictItem.Status;

        var ok = await repo.UpdateAsync(item, m => new {
            m.Label,
            m.Value,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
